import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:libflutter/bean/ChatSession.dart';
import 'package:libflutter/logger/logger.dart';
import 'package:libflutter/net/RDApi.dart';

class TestRefreshAndLoadMoreWidget extends StatelessWidget {
  const TestRefreshAndLoadMoreWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return ProviderScope(child: _MAppWidget());
  }
}

class _MAppWidget extends ConsumerStatefulWidget {
  @override
  ConsumerState<ConsumerStatefulWidget> createState() {
    return _MApp();
  }
}

class _MApp extends ConsumerState<_MAppWidget> {
  final _refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );

  List<ChatSession> _session = [];

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ref.listen(chatSession2Provider, (previous, next) {
      setState(() {
        if (next.value == null) return;
        _session.addAll(next.value!);
      });
    });
    return Scaffold(
        appBar: AppBar(
          title: const Text("上拉刷新，下拉加载"),
        ),
        body: EasyRefresh(
          onRefresh: () async {
            /// 看历史代码，不要将这里做成回掉的方式
            print(" 进行数据的请求  >> onRefresh >>> ");
            final notifier = ref.read(chatSession2Provider.notifier);
            await notifier.refresh();
            Fluttertoast.showToast(msg: "上拉刷新--完成");
          },
          onLoad: () async {
            if (mounted) {
              print(" 进行数据的请求  >> onLoad >>> ");
              final notifier = ref.read(chatSession2Provider.notifier);
              await notifier.loadMore();
              Fluttertoast.showToast(msg: "下拉加载--完成");
            }
          },
          child: ListView.builder(
              itemExtent: 50,
              itemCount: _session.length,
              itemBuilder: (BuildContext context, int index) {
                final item = _session[index];
                return Text(item.toString());
              }),
        ));
  }
}

/// 异步notice
class ChatSessionList2Provider extends AsyncNotifier<List<ChatSession>> {
  /// 初次构建需要提供一个默认的数据填充 build
  /// 这里进行一个开发 对话框的开发任务
  int _page = 1;

  @override
  FutureOr<List<ChatSession>> build() {
    return getSessionByPage();
  }

  Future<void> refresh() async {
    state = await AsyncValue.guard(() async {
      return getSessionByPage();
    });
  }

  Future<void> loadMore() async {
    state = await AsyncValue.guard(() async {
      return await getSessionByPage(page: _page + 1);
    });
  }

  // 获取第一页的对话框
  Future<List<ChatSession>> getSessionByPage({int page = 1}) async {
    return await Future.delayed(const Duration(seconds: 1), () {
      print(" 进行数据的请求 当前的page == ${page}");
      const pageSize = 20;
      var result = <ChatSession>[];
      for (var idx = 0; idx < pageSize * page; idx++) {
        result.add(ChatSession(idx, "$idx >>> Session"));
      }
      _page = page;
      return result;
    });
  }
}

final chatSession2Provider = AsyncNotifierProvider<ChatSessionList2Provider, List<ChatSession>>(
    () => ChatSessionList2Provider());
